from string import Template
from markupsafe import escape


def tmp(word, dicts, safe=True, clear=False):
    """安全的模板填充"""
    dicts = {k: escape(v) if safe else v for k, v in dicts.items()}
    string = Template(word).safe_substitute(dicts).split('${')
    pkgsql = (
        string[0] + ''.join([x.replace(x.split("}")[0], '')[1:] for x in string]))
    if clear:
        pkgsql = pkgsql.replace("''", "NULL")
    return pkgsql
